"""
A parallalized version of:
	repmasker_from_CL-dirs.pl
	from the SeqClust package (umbr_programs)
	
Here is the original perl code:

#!/usr/bin/perl -w

# spousti RepeatMasker na sadach sekvenci ulozenych v adresarich
# ktere maji stejny $dir_prefix
#
# ver. 02 - vyber databaze RepeatMaskeru
#
# (made from repmasker_z_adresaru_02.pl)

$dir_prefix = $ARGV[0];
if (defined $ARGV[1]) {
  $spec = $ARGV[1];
} else {
  $spec = "Viridiplantae";
}
$jm_sekvence = "reads.fas";

foreach $dir (glob("$dir_prefix")) {
  if ( -d $dir) {                      # overeni ze je to opravdu adresar
    
    print "-> running RepeatMasker at $dir/$jm_sekvence\n";
    $prikaz = "\${REPEAT_MASKER}/RepeatMasker $dir/$jm_sekvence -q -species $spec -pa 6 -dir $dir";
    $chyba = system($prikaz);
    if ($chyba) {
      print "---> Error running $prikaz\n";
    }
        
    print "...deleting temp files in $dir/$jm_sekvence\n";
    @vymazat = (".cat",".cat.all",".log",".masked",".ref");
    foreach $typ (@vymazat) {
      unlink("$dir/$jm_sekvence$typ");
    }
    rename("$dir/$jm_sekvence.out","$dir/RM-$jm_sekvence.out");
    rename("$dir/$jm_sekvence.tbl","$dir/RM-$jm_sekvence.tbl");
    
    # custom library:
    if (defined $ARGV[2]){
        
            print "-> running RepeatMasker at $dir/$jm_sekvence with custom library \n ";
            $prikaz = "\${REPEAT_MASKER}/RepeatMasker $dir/$jm_sekvence -q -lib $ARGV[2] -pa 6 -nolow -dir $dir";
            $chyba = system($prikaz);
            if ($chyba) {
              print "---> Error running $prikaz\n";
            }
                
            print "...deleting temp files in $dir/$jm_sekvence\n";
            @vymazat = (".cat",".cat.all",".log",".masked",".ref");
            foreach $typ (@vymazat) {
              unlink("$dir/$jm_sekvence$typ");
            }
            rename("$dir/$jm_sekvence.out","$dir/RM-custom_$jm_sekvence.out");
            rename("$dir/$jm_sekvence.tbl","$dir/RM-custom_$jm_sekvence.tbl");
    
        
    }
    
  }
}

@author:charles.hefer@gmail.com
"""
import sys, optparse, os, glob
from multiprocessing import Pool

def run_repeatmasker(directory):
	"""Runs RepeatMasker"""
	print("Running RepeatMasker at %s/%s" % (directory, jm_sekvence))
	cmd = """/usr/local/RepeatMasker/RepeatMasker %s/%s -q -species %s -pa 6 -dir %s""" % (directory, jm_sekvence, species, directory)
	os.system(cmd)
	
	vymazat = [".cat", ".cat.all",".log",".masked",".ref"]
	for typ in vymazat:
		os.unlink("%s/%s%s" % (directory,jm_sekvence, typ))
	
	

def __main__():
	parser = optparse.OptionParser()
	parser.add_option("-d","--dir_prefix", default=None, dest="dir_prefix",
		help="The directory prefix")
	parser.add_option("-s","--species", default="Viridiplantae", dest="species",
		help="The species to use")
	parser.add_option("-l","--library", default=None, dest="library",
		help="The custom library")
	parser.add_option("-t","--threads", default=4, dest="threads",
		help="The number of processes to start")
	(options, args) = parser.parse_args()
	
	global jm_sekvence #not sure why this name, but want to be constant in variable naming
	jm_sekvence = "reads.fas"
	global species
	species = options.species
	
	
	directories = []
	
	for directory in glob.glob(options.dir_prefix + "*"): #get all matches
		if os.path.isdir(directory): #get the directories
			directories.append(directory)
	
	pool = Pool(processes = int(options.threads))
	pool.map(run_repeatmasker, directories)
			
			
		
		
	
	
		


if __name__=="__main__":
	__main__()




